import { Component, OnInit } from '@angular/core';
import { BaseInputComponent } from '@shared/base-form/base-input/base-input.component';

@Component({
  selector: 'base-json-input',
  templateUrl: './base-json-input.component.html',
})
export class BaseJsonInputComponent extends BaseInputComponent implements OnInit {

  /*READEME: 配置项key可能会乱序，配置值如： {"key1":"value1","key2":"value2"}*/

  valueObj: any = {};

  constructor() {
    super();
  }

  ngOnInit() {
    this.dealEntity();
  }

  dealEntity() {
    let $this = this;
    this.entity.valueArr = [];
    if (this.entity.value) {
      this.valueObj = JSON.parse(this.entity.value);
      let keys = Object.keys($this.valueObj);
      keys.forEach((k) => {
        $this.entity.valueArr.push({ 'key': k, 'value': $this.valueObj[k] });
      });
    } else {
      $this.entity.valueArr = [];
    }
  }

  //json change begin  //whether any better solution
  changeValue(v) {
    this.valueObj[v.key] = v.value;
    this.entity.value = JSON.stringify(this.valueObj);
    this.validateForm.controls.value.setValue(this.entity.value);
    // console.log(this.entity)
  }

  changeKey(v, index) {
    let newValueObj: any = {};
    let keys = Object.keys(this.valueObj);
    for (let i = 0; i < keys.length; i++) {
      if (i == index) {
        newValueObj[v.key] = this.valueObj[keys[i]];
      } else {
        newValueObj[keys[i]] = this.valueObj[keys[i]];
      }
    }
    this.valueObj = newValueObj;
    this.entity.value = JSON.stringify(this.valueObj);
    this.validateForm.controls.value.setValue(this.entity.value);
    // console.log(this.entity)
  }

  remove(index) {
    this.entity.valueArr.splice(index, 1);
    this.valueObj = {};
    this.entity.valueArr.forEach((e) => {
      this.valueObj[e.key] = e.value;
    });
    this.entity.value = JSON.stringify(this.valueObj);
    this.validateForm.controls.value.setValue(this.entity.value);
    // console.log(this.entity)
  }

  add() {
    this.entity.valueArr.push({ 'key': '', 'value': '' });
    this.valueObj = {};
    this.entity.valueArr.forEach((e) => {
      this.valueObj[e.key] = e.value;
    });
    this.entity.value = JSON.stringify(this.valueObj);
    this.validateForm.controls.value.setValue(this.entity.value);
    // console.log(this.entity)

  }

  //json change end
}
